package com.cutepeer.notes;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cutepeer.lib.utils.NetworkUtils;
import com.cutepeer.lib.view.CustomToast;
import com.cutepeer.libonline.dialogs.ConfigDialog;
import com.cutepeer.libonline.server.KEY;
import com.cutepeer.notes.adapters.NoteAdapter;
import com.cutepeer.notes.adapters.items.NoteItem;
import com.cutepeer.notes.dialogs.DialogEditNote;
import com.cutepeer.notes.server.Connect;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class MainActivity extends FragmentActivity implements OnClickListener {

	private static Activity mActivity;
	private static FragmentManager fragmentManager;

	public static NoteAdapter noteAdapter;
	private static int currentPage = 1;
	private static boolean isLoadMore = false;
	private static boolean isLoading = true;
	private static boolean isCanLoadMore = true;

	private static PullToRefreshListView lvNotes;
	private static ListView lvNotesNormal;
	private static Button btReload;
	private static TextView tvEmpty;
	private static View footerView;
	private static ProgressBar pbLoad;

	private static int countRetry = 0;

	private String dialogEditNote = "DialogEditNote";

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		mActivity = this;
		fragmentManager = getSupportFragmentManager();
		vInitUI();
		vInitListener();
		vInitData(true);
	}

	private void vInitUI() {
		setContentView(R.layout.activity_main);
		ImageButton ibHeaderLeft = (ImageButton) findViewById(R.id.ibHeaderLeft);
		ImageButton ibHeaderRight = (ImageButton) findViewById(R.id.ibHeaderRight);
		ibHeaderLeft.setImageResource(R.drawable.ic_menu_white);
		ibHeaderRight.setImageResource(R.drawable.ic_add_white);
		TextView tvHeaderTitle = (TextView) findViewById(R.id.tvHeaderTitle);
		tvHeaderTitle.setText(getString(R.string.appName));

		lvNotes = (PullToRefreshListView) findViewById(R.id.lvNotes);
		lvNotesNormal = lvNotes.getRefreshableView();
		lvNotesNormal.setFastScrollEnabled(true);
		btReload = (Button) findViewById(R.id.btReload);
		tvEmpty = (TextView) findViewById(R.id.tvEmpty);
		pbLoad = (ProgressBar) findViewById(R.id.pbLoad);
		footerView = mActivity.getLayoutInflater().inflate(R.layout.ui_footer_load_post, null);


		lvNotes.setAdapter(null);

		ibHeaderLeft.setOnClickListener(this);
		ibHeaderRight.setOnClickListener(this);
		btReload.setOnClickListener(this);
	}

	private void vInitListener() {
		lvNotes.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(mActivity, System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				vInitTabNote(false);
			}
		});

		lvNotesNormal.setOnScrollListener(new OnScrollListener(){

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if (visibleItemCount != totalItemCount & firstVisibleItem + visibleItemCount == totalItemCount) {
					if (!isLoading && isCanLoadMore && NetworkUtils.isInternetConnected(mActivity)) {
						isLoadMore = true;
						currentPage = currentPage + 1;
						vInitData(false);
					}
				}
			}

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

		});

	}

	private static void vInitData(final boolean isShowProgress) {
		if (isShowProgress) {
			vUILoadingOpen();
		}

		isLoading = true;
		tvEmpty.setVisibility(View.GONE);
		btReload.setVisibility(View.GONE);

		new Thread(new Runnable() {
			@Override
			public void run() {
				final JSONObject jsonObject = Connect.get(mActivity, currentPage);
				mActivity.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						try {
							if (jsonObject != null && Integer.parseInt(jsonObject.getString(KEY.tagQueryResult)) == KEY.queryResultSuccess) {
								JSONArray jsonArray = jsonObject.getJSONArray("notes");
								if (!isLoadMore) {
									noteAdapter = new NoteAdapter(mActivity);
								}
								for(int i = 0; i < jsonArray.length(); i++){
									JSONObject json = jsonArray.getJSONObject(i);
									String noteId = json.getString("noteId");
									String noteText = json.getString("noteText");
									String noteTime = json.getString("noteTime");
									String userId =  json.getString(KEY.userId);
									String userAccount =  json.getString(KEY.userAccount);
									String userName =  json.getString(KEY.userName);
									String userCover =  json.getString(KEY.userCover);
									String userAvatar =  json.getString(KEY.userAvatar);
									noteAdapter.add(new NoteItem(noteId, noteText, noteTime,
											userId, userAccount, userName, userCover, userAvatar));
								}
								noteAdapter.notifyDataSetChanged();
								if (!isLoadMore) {
									lvNotes.setAdapter(noteAdapter);
								}
								if (lvNotesNormal.getFooterViewsCount() < 2) {
									lvNotesNormal.addFooterView(footerView);
								}
							} else {
								lvNotesNormal.removeFooterView(footerView);
								isLoadMore = false;
								isCanLoadMore = false;
							}

							if (jsonObject != null && Integer.parseInt(jsonObject.getString("total")) <= Integer.parseInt(jsonObject.getString("perpage"))) {
								lvNotesNormal.removeFooterView(footerView);
							}

							if (jsonObject != null && Integer.parseInt(jsonObject.getString("total")) == 0) {
								lvNotes.setAdapter(null);
								tvEmpty.setVisibility(View.VISIBLE);
							}

							if (jsonObject == null) {
								if (NetworkUtils.isInternetConnected(mActivity) && countRetry < 3) {
									countRetry = countRetry + 1;
									vInitData(true);
								} else {
									btReload.setVisibility(View.VISIBLE);
								}
								Log.i(MainActivity.class.getSimpleName(), "jsonObject is null, retry: " + Integer.toString(countRetry));
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							if (NetworkUtils.isInternetConnected(mActivity) && countRetry < 3) {
								countRetry = countRetry + 1;
								vInitData(true);
							} else {
								btReload.setVisibility(View.VISIBLE);
							}
							Log.i(MainActivity.class.getSimpleName(), "JSONException, retry: " + Integer.toString(countRetry));
							e.printStackTrace();
						}

						if (isShowProgress) {
							vUILoadingClose();
						}
						lvNotes.onRefreshComplete();
						isLoading = false;
					}
				});
			}
		}).start();
	}

	private static void vInitTabNote(boolean isShowProgress) {
		isLoadMore = false;
		isCanLoadMore = true;
		currentPage = 1;
		vInitData(isShowProgress);
	}

	public static void vRefresh() {
		lvNotes.setRefreshing();
	}

	private static void vUILoadingOpen() {
		pbLoad.setVisibility(View.VISIBLE);
	}

	private static void vUILoadingClose() {
		pbLoad.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()) {
		case R.id.ibHeaderLeft:

			break;

		case R.id.ibHeaderRight:
			if (!ConfigDialog.isDialogFragmentShowing(fragmentManager, dialogEditNote)) {
				new DialogEditNote().show(fragmentManager, dialogEditNote);
			}

		case R.id.btReload:
			if (NetworkUtils.isInternetConnected(mActivity)) {
				isLoadMore = false;
				isCanLoadMore = true;
				currentPage = 1;
				vInitData(true);
			} else {
				CustomToast.vToastNoInternet(mActivity);
			}
			break;
		}
	}
}
